import requests
import json
from pyquery import PyQuery as pq

UC_HOST = 'https://u.4399om.com/main/?r=access/index'
LOGIN_URL = 'https://u.4399om.com/main/?r=access/loginSubmit'


def login(user_name, password):
    """
    支持登陆并保存cookie
    :param user_name:
    :param password:
    :return:
    """
    doc = pq(url=UC_HOST, encoding='utf-8')
    # 获取csrf token
    csrf_token = doc("input[name='YII_CSRF_TOKEN']").val()
    data = {
        'UserID': user_name,
        'Password': password,
        'sysCrossLoginUrl': 'http://in.4399om.com/loginApi/crossLogin.php',
        'sys': 'in4399',
        'sysReturnUrl': 'http://in.4399om.com',
        'YII_CSRF_TOKEN': csrf_token,
    }
    rs = requests.post(url=LOGIN_URL, data=data)
    cookie = rs.cookies
    results = json.loads(rs.content)
    if 'code' not in results or results['code'] != 200:
        return False
    # 保存cookie
    php_session_id = cookie.get('PHPSESSID')
    
    return True
    pass
